package com.joeyzh.soundrecorder.audio;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.util.Log;

import com.joeyzh.soundrecorder.R;
import com.joeyzh.soundrecorder.bean.AudioModel;

import java.io.IOException;
import java.io.Serializable;
import java.util.TimerTask;

/**
 * 录音的 Service
 * <p>
 * Created by developerHaoz on 2017/8/12.
 */

public class RecordingService extends Service {

    private static final String LOG_TAG = "RecordingService";

    private String mFileName = null;
    private String mFilePath = null;
    private MediaRecorder mRecorder = null;

    private long mStartingTimeMillis = 0;
    private long mElapsedMillis = 0;
    private TimerTask mIncrementTimerTask = null;

    private AudioModel mRecordingModel;

    /**
     * 播放
     */
    private MediaPlayer mMediaPlayer;
    //播放
    private boolean isPlay = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isPlay = intent.getBooleanExtra("play", false);
        mRecordingModel = (AudioModel) intent.getSerializableExtra("recording");
        startRecording();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopRecording();
        super.onDestroy();
    }

    public void startRecording() {
        if (isPlay) {
            startPlaying();
            return;
        }

        if (null == mRecordingModel || mRecordingModel.getFilePath().isEmpty()) {
            mFileName = getString(R.string.default_file_name)
                    + "_" + (System.currentTimeMillis()) + ".mp4";
            mRecordingModel = new AudioModel(mFileName, mElapsedMillis);
        }
        mFilePath = mRecordingModel.getFilePath();
        mFileName = mRecordingModel.getFileName();
        mElapsedMillis = mRecordingModel.getElpased();

        //先释放上次资源
        if (null != mRecorder) {
            mRecorder.stop();
            mRecorder.release();
        }
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFilePath);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioChannels(1);
        mRecorder.setAudioSamplingRate(48000);
        mRecorder.setAudioEncodingBitRate(384000);

        try {
            mRecorder.prepare();
            mRecorder.start();
            mStartingTimeMillis = System.currentTimeMillis();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        Intent intent = new Intent();
        intent.setAction("com.joeyzh.imagepicker");
        intent.putExtra("isStart", true);
        sendBroadcast(intent);
    }

    /**
     * 开始播放
     */
    private void startPlaying() {
        if (null == mRecordingModel || mRecordingModel.getFilePath().isEmpty()) {
            return;
        }
        //先释放上一次的资源，防止资源占用
        stopPlaying();
        mMediaPlayer = new MediaPlayer();

        try {
            mMediaPlayer.setDataSource(mRecordingModel.getFilePath());
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlaying();
            }
        });
    }

    /**
     * 停止播放
     */
    private void stopPlaying() {
        if (null == mMediaPlayer) {
            return;
        }
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    /**
     * 停止录音
     */
    public void stopRecording() {
        stopPlaying();
        if (null == mRecorder) {
            return;
        }
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
        if (isPlay) {
            return;
        }
        //时间为默认时
        if (mElapsedMillis <= 0) {
            mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
            if (null == mRecordingModel) {
                mRecordingModel = new AudioModel(mFileName, mElapsedMillis);
            } else {
                //更新时间
                mRecordingModel.setElpased(mElapsedMillis);
            }
        }
        //广播调用
        Intent intent = new Intent();
        intent.setAction("audio");
        intent.putExtra("play", isPlay);
        intent.putExtra("isStart", false);
        intent.putExtra("recordingModel", (Serializable) mRecordingModel);
        sendBroadcast(intent);
    }


}
